/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.LogUtils;
import io.renren.common.validator.Assert;
import io.renren.config.ApiConfig;
import io.renren.dao.UserDao;
import io.renren.entity.UserEntity;
import io.renren.form.LoginForm;
import io.renren.service.UserService;
import io.renren.util.JwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {


    @Cacheable(value="userCache", key="'queryByMobile'+#mobile")
    @Override
    public UserEntity queryByMobile(String mobile) {
        LogUtils.debugPrint("进入数据库查询queryByMobile");
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
    }

    /**
     * Description: 清除缓存
     *
     * @author: afeng
     * @date: 2020/2/23 12:54
     */
    @CacheEvict(value = "userCache", key = "'queryByMobile'+#mobile")
    @Override
    public void cleanCacheQueryByMobile(String mobile) {
    }

    @Override
    public Map<String, Object> login(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("手机号或密码错误");
        }

        //获取登录token
        String token = JwtUtil.createToken(user.getUserId() + "", ApiConfig.TOKEN_KEY,
                ApiConfig.TOKEN_SECRET, ApiConfig.TOKEN_EXPIRE_TIME);

        Map<String, Object> map = new HashMap<>(2);
        map.put("token", token);
        map.put("expire", new Date(System.currentTimeMillis() + ApiConfig.TOKEN_EXPIRE_TIME));

        return map;
    }

}
